<?php
import('controller.class.php');
import('model.message.class.php');
import('view.poll.class.php');

if(DEBUG_MODE){
	define('POLL_SLEEP_TIME', 1);
}else{
	define('POLL_SLEEP_TIME',5);
}
// 需要打开自动输出，避免在缓冲区中缓存了。
class Poll extends Controller{
	var $view;

	function __construct(){
		$this->view = new ViewPoll();
	}

	public function action(){
		@set_time_limit(0);

		if(!$_SESSION['login']){
			//未登陆，错误。
			parent::displayByCode(POLL_F_NEED_LOGIN);
			return;
		}

		$reciver = $_SESSION['uuid'];

		ob_flush();
		flush();
		while (true){
// 		for($i=0;$i<3;$i++){
			log_d("Check for new message in loop $i");
			$msgs = ModelMessage::findMessagesByReciever($reciver);
			if(is_array($msgs) && count($msgs) > 0){
				log_d("Found ".count($msgs)." message(s) for uuid $uuid");
				foreach ($msgs as $msg){
					//逐条显示信息
					$view = $this->view->getMsgView($msg->content);
					parent::display($view);
					//标记未已发送
					$msg->mark2Send();
				}
				ob_flush();
				flush();
			}
			sleep(POLL_SLEEP_TIME);
			
		}


	}
}
?>